package cn.appsys.controller;

import cn.appsys.pojo.Version;
import cn.appsys.service.InfoService;
import cn.appsys.service.VersionService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;

@Controller
@RequestMapping("/version")
public class VersionController {

    @Resource
    InfoService infoService;
    @Resource
    VersionService versionService;

    @RequestMapping("/updateVersion")
    public String updateVersion(Version version, @RequestParam("attach") MultipartFile attach, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String apkLocPath = null;
        String downloadLink = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + java.io.File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();//原文件名
            String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            int fileSize = 900000000;
            if (attach.getSize() > fileSize) {//上传大小不得超过 50k
                request.setAttribute("fileUploadError", "* 上传文件过大！");
                return "developer/appinfoadd";
            } else if (suffix.equalsIgnoreCase("apk") || suffix == null) {//上传图片格式
                String fileName = StringUtils.substringBefore(version.getApkName(), ".apk") + "-" + version.getVersionNo() + ".apk";  //上传LOGO图片命名:apk名称.apk
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                } else {
                    targetFile.delete();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    request.setAttribute("fileUploadError", "* 上传失败！");
                    return "developer/appinfoadd";
                }
                apkLocPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                downloadLink = path + File.separator + fileName;
                version.setApkFileName(fileName);
            } else {
                request.setAttribute("fileUploadError", "* 上传文件格式不正确！");
                return "developer/appinfoadd";
            }
        }
        version.setCreationDate(new Date());
        version.setApkLocPath(apkLocPath);
        version.setDownloadLink(downloadLink);
        version.setCreatedBy(1L);
        Integer integer = versionService.updateVersion(version);
        if (integer > 0) {
            return "redirect:/info/devlist";
        }
        return "redirect:/user/toVersoinAdd?id=" + version.getAppId();
    }

    @RequestMapping("/addVersion")
    public String addVersion(Version version, @RequestParam("a_downloadLink") MultipartFile attach, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String apkLocPath = null;
        String downloadLink = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + java.io.File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();//原文件名
            String suffix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            int fileSize = 900000000;
            if (attach.getSize() > fileSize) {//上传大小不得超过 50k
                request.setAttribute("fileUploadError", "* 上传文件过大！");
                return "developer/appinfoadd";
            } else if (suffix.equalsIgnoreCase("apk") || suffix == null) {//上传图片格式
                String fileName = StringUtils.substringBefore(version.getApkName(), ".apk") + "-" + version.getVersionNo() + ".apk";//上传LOGO图片命名:apk名称.apk
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                } else {
                    targetFile.delete();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    request.setAttribute("fileUploadError", "* 上传失败！");
                    return "developer/appinfoadd";
                }
                apkLocPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                downloadLink = path + File.separator + fileName;
                version.setApkFileName(fileName);
            } else {
                request.setAttribute("fileUploadError", "* 上传文件格式不正确！");
                return "developer/appinfoadd";
            }
        }
        version.setCreationDate(new Date());
        version.setApkLocPath(apkLocPath);
        version.setDownloadLink(downloadLink);
        version.setCreatedBy(1L);
        Integer integer = versionService.addVersion(version);
        if (integer > 0) {
            infoService.updateVersionId(version.getAppId(), version.getId());
            infoService.updateStatus(version.getAppId(), 1L);
            return "redirect:/info/devlist";
        }
        return "redirect:/user/toVersoinAdd?id=" + version.getAppId();
    }

    @RequestMapping("/delApk")
    @ResponseBody
    public Object delApk(@RequestParam("id") Long id, HttpServletRequest request) {
        String str = "failed";
        try {
            Integer integer = versionService.delApk(id);
            if (integer > 0) {
                str = "success";
            }
        } catch (Exception e) {
            str = "failed";
            e.printStackTrace();
            throw new Exception();
        } finally {
            return JSON.toJSONString(str);
        }
    }
}
